#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include "regex_utils.h"

int regex(const char *str, const char *pattern, int num_match, subexp_t *subexp, int cflags)
{
    int i, match_len, errno, errsv;
    regex_t strcomp;
    regmatch_t matchptr[num_match];

    subexp->match = malloc(num_match * sizeof(subexp_t));
    subexp->len = 0;
    if (!regcomp(&strcomp, pattern, cflags)) {
        if(!regexec(&strcomp, str, num_match, matchptr, 0)) {
            for(i = 0; i < num_match; i++) {
                match_len = matchptr[i].rm_eo - matchptr[i].rm_so;
                subexp->match[i] = (char *)malloc((match_len + 1) * sizeof(char));
                strncpy(subexp->match[i], str + matchptr[i].rm_so, match_len);
                subexp->match[i][match_len] = '\0';
                subexp->len++;
            }
        } else {
            return -1;
        }
    } else {
        printf("Regex compilation error\n");
        return -1;
    }
    regfree(&strcomp);
    return 0;
}

int free_subexp_t(subexp_t *subexp)
{
    int i;
    for (i = 0; i < subexp->len; i++)
        free(subexp->match[i]);
    free(subexp->match);
}

